package com.homedo.microservice.open.service.gateway.zuul.task;


import com.google.common.collect.Lists;
import com.homedo.common.util.Detect;
import com.homedo.microservice.open.service.gateway.bean.enums.forroutedomain.StatusEnum4RouteDomain;
import com.homedo.microservice.open.service.gateway.bean.po.RouteDomain;
import com.homedo.microservice.open.service.gateway.persistence.dao.RouteDomainDao;
import com.homedo.microservice.open.service.gateway.zuul.conf.DomainConf;
import com.homedo.microservice.open.service.gateway.zuul.conf.ZuulCommonConf;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.Map;

@Component
public class DomainConfUpdateTask {
    @Autowired
    private RouteDomainDao routeDomainDao;
    @Autowired
    private ZuulCommonConf zuulCommonConf;

    private static final Logger LOGGER = LoggerFactory.getLogger(DomainConfUpdateTask.class);

    @Scheduled(cron = "0/6 * * * * ?")
    public void zuulCommonConfUpdateTask() {
        StopWatch stopWatch = null;
        if (zuulCommonConf.getApplicationLogDetail().get()) {
            stopWatch = new StopWatch();
            stopWatch.start();
            LOGGER.info("更新域名配置开始:时间[" + new DateTime().toString("yyyy-MM-dd HH:mm:ss.SSS") + "]");
        }


        this.doSchedule();

        if (zuulCommonConf.getApplicationLogDetail().get()) {
            if (stopWatch != null) {
                stopWatch.stop();
                LOGGER.info("更新域名配置结束:时间[" + new DateTime().toString("yyyy-MM-dd HH:mm:ss.SSS") + "],耗时[" + stopWatch.getTotalTimeMillis() + "毫秒]");
            }
        }

    }

    private void doSchedule() {
        List<RouteDomain> routeDomains = routeDomainDao.getListByApplication(zuulCommonConf.getApplicationName(), Lists.newArrayList(StatusEnum4RouteDomain.EFFECTIVE));
        Map<String, String> confs = DomainConf.getInstance().getConfs();

        if (!Detect.notEmpty(routeDomains)) {
            confs.clear();
            return;
        }


        routeDomains.forEach(e -> {
            confs.put(e.getDomain(), e.getDomain());
        });
    }

}
